package com.zhuyp.spring.boot.dao.Impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;

import com.zhuyp.spring.boot.dao.EntityDao;
import com.zhuyp.spring.boot.entity.Entity;

@Component
public class EntityDaoImpl implements EntityDao{

	@Autowired
	private MongoTemplate mongoTemplate;

	@Override
	public void add(Entity entity) {
		mongoTemplate.save(entity);
	}

	@Override
	public void update(Entity entity) {
		Query query = new Query(Criteria.where("id").is(entity.getId()));
		Update update = new Update().set("name", entity.getName());
		mongoTemplate.updateFirst(query, update, Entity.class);
	}

	@Override
	public void delete(Entity entity) {
		Query query = new Query(Criteria.where("id").is(entity.getId()));
		mongoTemplate.remove(query, Entity.class);
	}

	@Override
	public Entity findEntityByName(Entity entity) {
		Query query = new Query(Criteria.where("name").is(entity.getName()));
		entity = mongoTemplate.findOne(query, Entity.class);
		return entity;
	}

}
